package com.example.backend.util;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.backend.dao.UserRepository;
import com.example.backend.pojo.User;
import com.google.gson.Gson;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.hibernate.service.spi.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;


public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private UserRepository userRepository;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler){
        String token = request.getHeader("token");
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        // 执行认证
        if (StrUtil.isBlank(token)) {
            sendErrorResponse(response, "无token，请重新登录");
            throw new ServiceException("无token，请重新登录");
        }
        // 获取 token 中的 user id
        String username;
        try {
            username = JWT.decode(token).getClaim("username").asString();
        } catch (JWTDecodeException j) {
            sendErrorResponse(response, "token验证失败，请重新登录");
            throw new ServiceException("token验证失败，请重新登录");
        }
        // 根据token中的userid查询数据库
        User user = userRepository.findUserByUsername(username);
        if (user == null) {
            sendErrorResponse(response, "用户不存在，请重新登录");
            throw new ServiceException("用户不存在，请重新登录");
        }
        // 用户密码加签验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token); // 验证token
        } catch (JWTVerificationException e) {
            sendErrorResponse(response, "token验证失败，请重新登录");
            throw new ServiceException("token验证失败，请重新登录");
        }
        return true;
    }
    private void sendErrorResponse(HttpServletResponse response, String msg) {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        String json = new Gson().toJson(new Response<>(Response.FAIL,msg,null));
        try {
            response.getWriter().write(json);
        } catch (Exception e) {
            // 处理异常
        }
    }
}
